#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
时间间隔计算器
计算两个时间点之间的时间差
"""

def get_valid_input(prompt, min_val, max_val):
    """
    获取有效的输入值
    """
    while True:
        try:
            value = int(input(prompt))
            if min_val <= value <= max_val:
                return value
            else:
                print(f"请输入{min_val}到{max_val}之间的整数")
        except ValueError:
            print("请输入有效的整数")

def calculate_time_interval():
    """
    计算时间间隔
    """
    print("=" * 40)
    print("      时间间隔计算器")
    print("=" * 40)
    
    # 获取起始时间
    print("\n【起始时间】")
    start_hour = get_valid_input("请输入小时数 (0-23): ", 0, 23)
    start_minute = get_valid_input("请输入分钟数 (0-59): ", 0, 59)
    
    # 获取结束时间
    print("\n【结束时间】")
    end_hour = get_valid_input("请输入小时数 (0-23): ", 0, 23)
    end_minute = get_valid_input("请输入分钟数 (0-59): ", 0, 59)
    
    # 计算总分钟数
    start_total_minutes = start_hour * 60 + start_minute
    end_total_minutes = end_hour * 60 + end_minute
    
    # 计算时间间隔（处理跨天情况）
    duration_minutes = end_total_minutes - start_total_minutes
    if duration_minutes < 0:
        duration_minutes += 24 * 60  # 加上一天的分钟数
    
    # 转换为小时和分钟
    duration_hour = duration_minutes // 60
    duration_minute = duration_minutes % 60
    
    # 格式化输出
    print("\n" + "=" * 40)
    print(f"起始时间: {start_hour:02d}:{start_minute:02d}")
    print(f"结束时间: {end_hour:02d}:{end_minute:02d}")
    print("-" * 40)
    
    # 输出结果
    if duration_hour == 0 and duration_minute == 0:
        print("时间间隔: 0分钟（两个时间点相同）")
    else:
        result_parts = []
        if duration_hour > 0:
            result_parts.append(f"{duration_hour}小时")
        if duration_minute > 0:
            result_parts.append(f"{duration_minute}分钟")
        
        print(f"时间间隔: {'、'.join(result_parts)}")
    
    print("=" * 40)
    
    return (start_hour, start_minute, end_hour, end_minute, duration_hour, duration_minute)

def main():
    """
    主函数
    """
    history = []
    
    while True:
        # 计算时间间隔
        result = calculate_time_interval()
        history.append(result)
        
        # 显示历史记录
        if len(history) > 1:
            print(f"\n最近计算历史（共{len(history)}条）:")
            print("-" * 60)
            print(f"{'序号':<4} {'起始时间':<12} {'结束时间':<12} {'间隔'}")
            print("-" * 60)
            
            # 显示最近的3条记录
            for i, record in enumerate(reversed(history[-3:]), 1):
                start_h, start_m, end_h, end_m, dur_h, dur_m = record
                start_str = f"{start_h:02d}:{start_m:02d}"
                end_str = f"{end_h:02d}:{end_m:02d}"
                
                duration_parts = []
                if dur_h > 0:
                    duration_parts.append(f"{dur_h}h")
                if dur_m > 0:
                    duration_parts.append(f"{dur_m}m")
                
                duration_str = "".join(duration_parts) if duration_parts else "0m"
                print(f"{len(history)-i+1:<4} {start_str:<12} {end_str:<12} {duration_str}")
        
        # 询问是否继续
        while True:
            choice = input("\n是否继续计算？(y/n): ").lower()
            if choice in ['y', 'n']:
                break
            print("请输入'y'或'n'")
        
        if choice == 'n':
            print("\n感谢使用时间间隔计算器！")
            break

if __name__ == "__main__":
    main()
